package edu.zut.main.thread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.io.IOException;

public class ThreadDemo1 {
    public static void main(String[] args) {
        //创建多个线程
        ThreadImgDown threadImgDown1 = new ThreadImgDown("https://img1.baidu.com/it/u=172337203,4011950556&fm=26&fmt=auto&gp=0.jpg", "1.jpg");
        ThreadImgDown threadImgDown2 = new ThreadImgDown("https://img1.baidu.com/it/u=2729200364,1701331398&fm=26&fmt=auto&gp=0.jpg", "2.jpg");
        ThreadImgDown threadImgDown3 = new ThreadImgDown("https://img1.baidu.com/it/u=2397343483,1770497010&fm=26&fmt=auto&gp=0.jpg", "3.jpg");

        //启动线程   只是让当前线程处于就绪
        threadImgDown1.start();

        threadImgDown2.start();

        threadImgDown3.start();
    }

}
/**
 * 模拟在多线程之下同时下载多张图片
 * 一、继承Thread实现多线程
 *     重写run
 *     创建线程对象
 *     调用start
 */
class ThreadImgDown extends Thread{

    private String url;
    private String pathName;

    public ThreadImgDown(String url, String pathName) {
        this.url = url;
        this.pathName = pathName;
    }

    //run 线程任务，自动执行的
    @Override
    public void run() {
        new ImgDown().download(url,pathName);
        System.out.println(pathName + "完成");
    }
}

//提供的就是下载任务
class ImgDown{

    /**
     * 下载
     * @param url 资源路劲
     * @param pathName 本地保存路劲
     */
    public void download(String url,String pathName){
        try {
            //从url上将资源拷贝到本地pathName
            FileUtils.copyURLToFile(new URL(url),new File(pathName));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
